package com.bitsbazaar.controller;

import java.io.IOException;
import java.sql.Blob;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.rowset.serial.SerialException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.bitsbazaar.entity.Image;
import com.bitsbazaar.entity.Product;
import com.bitsbazaar.entity.User;
import com.bitsbazaar.manager.ImageManager;
import com.bitsbazaar.manager.ProductManager;
import com.bitsbazaar.manager.UserManager;

@Controller
public class SellController {

	@Autowired
	private UserManager UserManager;
	@Autowired
	private ImageManager imageManager;
	@Autowired
	private ProductManager productManager;

	@RequestMapping(value = "/createListing", method = RequestMethod.GET)
	public ModelAndView createListing(HttpServletRequest request,
			WebRequest webRequest, SessionStatus status,
			ModelAndView modelAndView) {
		String message = "createListing";
		User user = (User) request.getSession().getAttribute("userObject");
		if (user != null) {
			System.out.println(message + user.getEmail());
			return new ModelAndView("createListing", "command", new Product());
		} else {
			System.out.println(message);
			request.getSession().setAttribute("signUpBeforeSell",
					"Wanna Sell Something ? Please Login First");
			return new ModelAndView("login", "command", new User());
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView upload(Product product,
			MultipartHttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView)
			throws SerialException, SQLException {

		// 0. notice, we have used MultipartHttpServletRequest

		// 1. get the files from the request object
		Iterator<String> itr = request.getFileNames();
		Long imageid = 0L;

		System.out.println("Upload controller");
		while (itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() + " uploaded!");

			try {
				// just temporary save file info into ufile
				byte[] bytes = mpf.getBytes();
				Image image = new Image();
				image.setParentId(2L);
				image.setParentType("category");
				Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes);
				image.setImage(blob);
				imageid = imageManager.createImage(image);

				product.setApproved(0);
				product.setAvailable(1);
				product.setMainImgId(imageid);

				long time = new java.util.Date().getTime();
				product.setCreatedDate(new Date(time));
				User user = (User) request.getSession().getAttribute(
						"userObject");
				product.setUserId(user.getId());
				Long productid = productManager.createProduct(product);
				Image imagedb=imageManager.getImageById(imageid);
				imagedb.setParentId(productid);
				imageManager.updateImage(imagedb);
				Product dbProduct=productManager.getProductById(productid);
		        List<Image>  images=imageManager.getImageByParentId(productid);
		        // Adding model objects
		        modelAndView.addObject("product",dbProduct);
		        modelAndView.addObject("user",user);
		        modelAndView.addObject("image",(Image)images.get(0));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		modelAndView.setViewName("productView");
		return modelAndView;
	}
}
